package com.io.nio.mappedByteBuffer.ionio;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class WriteMethod {

	/**
	 * io
	 * 
	 * @param emp
	 * @return
	 */
	public boolean addRecord_IO(RandomAccessFile journal, Employee emp) {
		try {
			byte[] last = emp.getLast().getBytes();
			byte[] first = emp.getFirst().getBytes();
			byte[] comments = emp.getComments().getBytes();

			// Next write the data
			journal.writeInt(last.length);
			journal.write(last);
			journal.writeInt(first.length);
			journal.write(first);
			journal.writeInt(emp.getId());
			journal.writeInt(emp.getZip());
			if (emp.isEmployed())
				journal.writeByte(1);
			else
				journal.writeByte(0);
			journal.writeInt(comments.length);
			journal.write(comments);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * nio
	 * 
	 * @param channel
	 * @param data
	 * @param emp
	 * @return
	 */
	public boolean addRecord_NIO(FileChannel channel, ByteBuffer data,
			Employee emp) {
		try {
			data.clear();

			byte[] last = emp.getLast().getBytes();
			byte[] first = emp.getFirst().getBytes();
			byte[] comments = emp.getComments().getBytes();

			data.putInt(last.length);
			data.put(last);
			data.putInt(first.length);
			data.put(first);
			data.putInt(emp.getId());
			data.putInt(emp.getZip());
			byte employed = 0;
			if (emp.isEmployed())
				employed = 1;
			data.put(employed);
			data.putInt(comments.length);
			data.put(comments);
			data.flip();

			// Fist write the header
			channel.write(data);

			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * MappedByteBuffer
	 * 
	 * @param mbb
	 * @param emp
	 * @return
	 */
	public boolean addRecord_MBB(MappedByteBuffer mbb, Employee emp) {
		try {
			byte[] last = emp.getLast().getBytes();
			byte[] first = emp.getFirst().getBytes();
			byte[] comments = emp.getComments().getBytes();

			mbb.putInt(last.length);
			mbb.put(last);
			mbb.putInt(first.length);
			mbb.put(first);
			mbb.putInt(emp.getId());
			mbb.putInt(emp.getZip());
			byte employed = 0;
			if (emp.isEmployed())
				employed = 1;
			mbb.put(employed);
			mbb.putInt(comments.length);
			mbb.put(comments);

			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

}
